package com.lab.forthreadpool;


import com.lab.NoobChain;

/**
 * @author weiwei
 */

public class MyRunnable implements Runnable {
    private int A;
    private int B;
    private double val;

    public MyRunnable(int a, int b, double val) {
        A = a;
        B = b;
        this.val = val;
    }

    @Override
    public void run() {
        Transaction transaction = null;
        long startTime = System.currentTimeMillis();
        NoobChain.startTime = Math.min(NoobChain.startTime, startTime);

        //钱包锁
        while (!NoobChain.tryGetLock(A, B)) ;

        //将NoobChain中的UTXOs整合到自己的钱包中
        NoobChain.wallets.get(A).getBalance();
        NoobChain.wallets.get(B).getBalance();

        //生成 A->B val 的交易类
        transaction = NoobChain.wallets.get(A).sendFunds(NoobChain.wallets.get(B).publicKey, val);
        if (!transaction.processTransaction()) {
            System.out.println("交易失败！");
        }
        //释放锁
        NoobChain.locks[A].unlock();
        NoobChain.locks[B].unlock();

        //区块锁
        synchronized (NoobChain.obj) {
            Block block = null;
            if (NoobChain.blockchain.size() != 0) {
                block = new Block(NoobChain.blockchain.get(NoobChain.blockchain.size() - 1).hash);
            } else {
                block = new Block(NoobChain.genesis.hash);
            }
            block.transactions.add(transaction);
            NoobChain.addBlock(block);
        }
        long endTime = System.currentTimeMillis();
        NoobChain.endTime = Math.max(endTime, NoobChain.endTime);
    }
}


